package 算法.leetcode.offer.nk;

import 算法.leetcode.offer.base.ListNode;

/**
 * @author lchenglong
 * @date 2022/3/21
 */
public class BM2 {

    public static void main(String[] args) {
        BM2 instance = new BM2();
        ListNode head = ListNode.init(new int[]{3,1,3,4,1,4,-1});
        ListNode listNode = instance.reverseBetween(head, 3, 7);
        ListNode.print(listNode);
    }

    public ListNode reverseBetween(ListNode head, int m, int n) {
        // write code here
        if (m == n) return head;
        ListNode mNode=null,nNode = null,cur = head,pre = null;
        for (int i=0;i<n;i++){
            if (i == m-1) {
                mNode = cur;
            }
            pre = cur;
            cur = cur.next;
        }
        if (cur !=null)pre.next = null;
        ListNode p = null;
        while (mNode!=null){
            ListNode tmp = mNode.next;
            mNode.next = p;
            p = mNode;
            if (tmp==null)break;
                mNode = tmp;
        }
        if (m==1) {
            head = mNode;
        } else {
            ListNode s = head;
            for (int i=0;i<m-2;i++){
                s = s.next;
            }
            s.next = mNode;
        }
        while (mNode.next!=null)mNode = mNode.next;
        mNode.next = cur;
        return head;
    }
}
